<template>
  <div>
    <div class="search">
      <input class="search-input" type="text" v-model="keyword" placeholder="输入城市名或拼音">
    </div>
    <div class="search-result" v-show="keyword" ref="search">
      <ul>
        <li class="search-item" v-for="item of resultList" :key="item.id" @click="cityChange(item.name)">{{item.name}}</li>
        <li class="search-item border-bottom" v-show="hasNoData">
          没有找到匹配数据
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapState,mapMutations } from "vuex"

export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data: function(){
    return {
      resultList: [],
      keyword: '',
      timer: null
    }
  },
  computed: {
    hasNoData () {
      return !this.resultList.length
    }
  },
  methods: {
    ...mapMutations(['cityUpdata']),
    cityChange (cityName) {
      localStorage.city = cityName;
      this.cityUpdata(cityName);
      this.$router.push('/');
    }
  },
  watch: {
    keyword: function(){
      if(this.timer){
        clearTimeout(this.timer);
      }
      if (!this.keyword) {
        this.resultList = []
        return
      }
      this.timer = setTimeout(() => {
        const result = [];
        for(let i in this.cities){
          this.cities[i].forEach( (element, index) => {
            if(element.name.indexOf(this.keyword) > -1 || element.spell.indexOf(this.keyword) > -1){
                result.push(element);
              }
            });
        }
        this.resultList = result;
      },100)
      
      return
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search, {click: true})
  }

}
</script>

<style lang="stylus" scoped>

  @import '~styles/varibles.styl'
.search
  height: .72rem;
  padding: 0 0.1rem;
  background:$bgColor;
  .search-input
    box-sizing: border-box;
    width: 100%;
    text-align: center;
    height: .62rem;
    line-height: .62rem;
    border-radius:  .06rem;
    padding: 0 0.1rem;
    color: #666;
 .search-result
    z-index: 1
    overflow: hidden
    position: absolute
    top: 1.58rem
    left: 0
    right: 0
    bottom: 0
    background: #eee
    .search-item
      line-height: .62rem
      padding-left: .2rem
      background: #fff
      color: #666

</style>
